//
//  LGNetworkingManager.m
//  LGNetworkDemo
//
//  Created by dangwc on 2019/5/15.
//  Copyright © 2019 dangwc. All rights reserved.
//

#import "LGNetworkingManager.h"

@implementation LGNetworkingManager

+ (LGNetworkingManager *)shareNetworking{
    static LGNetworkingManager * manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[LGNetworkingManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/plain",nil];
    });
    return manager;
}

+(void)GETRequestUrl:(NSString *)urlString
              parameters:(id _Nullable)parameters
                 success:(void (^)(id _Nonnull))success
                 failure:(void (^)(NSError * _Nonnull))failure{
    [self lg_httpRequestMethod:@"GET" url:urlString parameters:parameters success:^(id _Nonnull responseObject) {
        success(responseObject);
    } failure:^(NSError * _Nonnull error) {
        failure(error);
    }];
    
  
    
}


+(void)POSTRequestUrl:(NSString *)urlString
               parameters:(id)parameters
                  success:(void (^)(id _Nonnull))success
                  failure:(void (^)(NSError * _Nonnull))failure{
    
    [self lg_httpRequestMethod:@"POST" url:urlString parameters:parameters success:^(id _Nonnull responseObject) {
       success(responseObject);
    } failure:^(NSError * _Nonnull error) {
        failure(error);
    }];
}



+(void)lg_httpRequestMethod:method
                        url:(NSString *)urlString
                 parameters:(id)parameters
                    success:(void (^)(id _Nonnull))success
                    failure:(void (^)(NSError * _Nonnull))failure{
    
    NSURL *requestUrl = [NSURL URLWithString:urlString];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:requestUrl];
    request.HTTPMethod = method;
    //设置其他参数按照项目组内部网络请求规则添加具体参数
    //[request setValue:@"" forHTTPHeaderField:@"secret"];
    //设置超时时间
    request.timeoutInterval = 10;
    //设置请求体
    NSString  *query = AFQueryStringFromParameters(parameters);
    if (parameters) {
        if ([method isEqualToString:@"GET"]) {
                if (query && query.length > 0) {
                    request.URL = [NSURL URLWithString:[[request.URL absoluteString] stringByAppendingFormat:request.URL.query ? @"&%@" : @"?%@", query]];
                }
            } else {
                if (![request valueForHTTPHeaderField:@"Content-Type"]) {
                    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
                }
               [request setHTTPBody:[query dataUsingEncoding:NSUTF8StringEncoding]];
            }
        }
    NSURLSessionDataTask *sessionDataTask = [[self shareNetworking] dataTaskWithRequest:request uploadProgress:^(NSProgress * _Nonnull uploadProgress) {
        //暂无业务需求，若需要请自行拓展
    } downloadProgress:^(NSProgress * _Nonnull downloadProgress) {
        //暂无业务需求，若需要请自行拓展
    } completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        if (error) {
            failure(error);
        }else{
            success(responseObject);
        }
    }];
    [sessionDataTask resume];
}

+(void)uploadDataWithRequest:(NSString *)urlString
               dataParmeters:(NSDictionary *)dataParnemts
                    progress:(void (^)(float))progress
                     success:(void (^)(id _Nonnull))success
                     failure:(void (^)(NSError * _Nonnull))failure{

    NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:urlString parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        [dataParnemts enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
            if ([obj isKindOfClass:[NSData class]]) {
                //图片上传(图片上传示例)
                [formData appendPartWithFileData:obj name:key fileName:key mimeType:@"image/jpeg"];
            }else{
                //文本
                [formData appendPartWithFormData:[obj dataUsingEncoding:kCFStringEncodingUTF8] name:key];
                //本地文件
                //[formData appendPartWithFileURL:[NSURL fileURLWithPath:@"xxxx/fileName.text"] name:@"file" fileName:@"fileName" mimeType:@"text/plain" error:nil];
            }
        }];
    } error:nil];
    
    NSURLSessionDataTask *uploadTask = [[self shareNetworking] dataTaskWithRequest:request uploadProgress:^(NSProgress * _Nonnull uploadProgress) {
         progress(uploadProgress.fractionCompleted);
    } downloadProgress:nil completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        if (error) {
            failure(error);
        } else {
            NSDictionary *objf = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:NULL];
            success(objf);
        }
    }];
    [uploadTask resume];
}

@end
